import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:speed_random/app_styles.dart';
import 'package:speed_random/colors_data.dart';
import 'package:speed_random/common/common_fuc.dart';
import 'package:speed_random/global_data.dart';
import 'package:speed_random/pages/home/setting/debug_page.dart';
import 'package:share_plus/share_plus.dart';
import 'package:speed_random/widgets/zdy_select_mp3_confirm.dart';
import 'package:url_launcher/url_launcher.dart';

import 'logic.dart';
import 'state.dart';

// ... 已有导入部分保持不变 ...

class SettingPage extends StatelessWidget {
  SettingPage({Key? key}) : super(key: key);

  final SettingLogic logic = Get.put(SettingLogic());
  final SettingState state = Get.find<SettingLogic>().state;

  int tapCount = 0;
  DateTime? lastTapTime;

  @override
  Widget build(BuildContext context) {
  //  _loadAd();
    return Scaffold(
      appBar: AppBar(
        title: GestureDetector(
          onTap: () async{
            final now = DateTime.now();
            if (lastTapTime == null || now.difference(lastTapTime!) > Duration(seconds: 5)) {
              tapCount = 0;
            }
            tapCount++;
            lastTapTime = now;
            if (tapCount >= 5) {
              tapCount = 0;
              Get.to(()=>DebugPage());
            }
          },
          child:Text("全局设置".tr),
        )
      ),

      body:
          Column(
        children: [
       // ... existing code ...

// ... existing code ...


          Expanded(child: ListView(

            children: [
              // 声音设置
              ListTileZdy(
            title: Text('通用背景音乐'.tr,style: TextStyle(fontSize: 16,color: AppStyles.colorPageText)),
            trailing: Obx(()=>Text(
              state.sound_path_name.value.tr,
                style: TextStyle(fontSize: 16,color: AppStyles.colorPageText)
            )),
            leading: Icon(Icons.volume_up,color: AppStyles.colorPageText),
            onTap: () {

              zdySelectMp3Confirm(context, globalData.soundPath, mp3s: colorsData.getSound(),dialogTitle: "通用背景音乐".tr, (mp3path,mp3name) {

                globalData.soundPath=mp3path;
                globalData.soundPathName=mp3name;
                state.sound_path_name.value=mp3name;
                logic.saveSoundSetting();
              });
            },
          ),
              // 声音设置
              ListTileZdy(
                title: Text('通用决定音'.tr,style: TextStyle(fontSize: 16,color: AppStyles.colorPageText)),
                trailing: Obx(()=>Text(
                  state.sound_success_path_name.value.tr,
                    style: TextStyle(fontSize: 16,color: AppStyles.colorPageText)
                )),
                leading: Icon(Icons.volume_up,color: AppStyles.colorPageText),
                onTap: () {

                  zdySelectMp3Confirm(context, globalData.soundSuccessPath, mp3s: colorsData.getSoundSuccess(),dialogTitle: "通用决定音".tr, (mp3path,mp3name) {
                    globalData.soundSuccessPath=mp3path;
                    globalData.soundSuccessPathName=mp3name;
                    state.sound_success_path_name.value=mp3name;
                    logic.saveSoundSetting();
                  });
                },
              ),
              ListTileZdy(
                title: Text('语言设置'.tr+"(30+)",style: TextStyle(fontSize: 16,color: AppStyles.colorPageText)),
                trailing: Obx(()=>Text(
                  state.currentLanguage_name.value.tr,
                  style: TextStyle(fontSize: 16,color: AppStyles.colorPageText),
                )),
                leading: Icon(Icons.language,color: AppStyles.colorPageText),
                onTap: () {
                  Get.bottomSheet(
                    Container(
                      color:Colors.white,
                      padding: EdgeInsets.all(16),
                      child: ListView( // 使用 ListView 替换 Column
                        shrinkWrap: true, // 使 ListView 自适应内容高度
                        children: [
                          Text('选择语言'.tr+"(30+)", style: TextStyle(fontSize: 18, color: AppStyles.colorPageText)),
                          SizedBox(height: 16),
                          Obx(() => Column(
                            children: state.currentLanguages.map((lang) => RadioListTile(
                              title: Text(lang['name']!.tr+"  (${lang['value']})", style: TextStyle(fontSize: 16, color: AppStyles.colorPageText)),
                              value: lang['value'],
                              groupValue: state.currentLanguage.value,
                              onChanged: (value) {
                                state.currentLanguage.value = value as String;
                                state.currentLanguage_name.value=lang['name']!;
                                logic.changeLanguage();
                              },
                            )).toList(),
                          )),
                        ],
                      ),
                    ),
                  );
                },
              ),

              // 主题切换
              ListTileZdy(
                title: Text('主题设置'.tr,style: TextStyle(fontSize: 16,color: AppStyles.colorPageText)),
                trailing: Obx(()=>Container(
                  width: 20,
                  height: 20,
                  decoration: BoxDecoration(
                    color: commonFuc.hexToColor(state.currentThemeBg.value),
                    borderRadius: BorderRadius.circular(8),
                  ),
                )),
                leading: Icon(Icons.color_lens,color: AppStyles.colorPageText),
                onTap: () {

                  Get.bottomSheet(
                Container(
                  color: AppStyles.colorPagebg,
                  padding: EdgeInsets.all(16),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text('选择主题'.tr, style: TextStyle(fontSize: 18,color: AppStyles.colorPageText)),
                      SizedBox(height: 16),
                      Obx(() => RadioListTile(
                        title: Text('浅色主题'.tr, style: TextStyle(fontSize: 16,color: AppStyles.colorPageText)),
                        value: ThemeMode.light,
                        groupValue: state.currentTheme.value,
                        onChanged: (value) {
                          state.currentTheme.value = value as ThemeMode;
                          logic.changeTheme();
                        },
                      )),
                      Obx(() => RadioListTile(
                        title: Text('深色主题'.tr, style: TextStyle(fontSize: 16,color: AppStyles.colorPageText)),
                        value: ThemeMode.dark,
                        groupValue: state.currentTheme.value,
                        onChanged: (value) {
                          state.currentTheme.value = value as ThemeMode;
                          logic.changeTheme();
                        },
                      )),
                    ],
                  ),
                ),
              );

                },
              ),




              // 新增用户评价选项
              if("${globalData.appInfo.ch?.rateUrl}".length>6)ListTileZdy(
                title: Row(
                  children: [
                    Expanded(child: Text('喜欢？😍请给我们五星'.tr,style: TextStyle(fontSize: 16,color: AppStyles.colorPageText)),),
                    Expanded(child: SizedBox()),
                    Icon(Icons.star,color: Colors.yellow,),
                    Icon(Icons.star,color: Colors.yellow,),
                    Icon(Icons.star,color: Colors.yellow,),
                    Icon(Icons.star,color: Colors.yellow,),
                    Icon(Icons.star,color: Colors.yellow,),
                  ],
                ),
                leading: Icon(Icons.star,color: AppStyles.colorPageText),

                onTap: () {
                  launchUrl(Uri.parse("${globalData.appInfo.ch?.rateUrl}")); //
                },
              ),



              ListTileZdy(
                title: Row(
                  children: [
                    Text('分享/推荐'.tr,style: TextStyle(fontSize: 16,color: AppStyles.colorPageText)),
                    Expanded(child: SizedBox()),

                  ],
                ),
                leading: Icon(Icons.share,color: AppStyles.colorPageText),

                onTap: () async{

                  final shareText = globalData.appShareText.tr;
commonFuc.shareImageWithText(text: shareText, title: globalData.appName,filePath: "assets/images/logo100x100.png",url: "${globalData.appInfo.ch?.updateUrl}");
                },
              ),


              /* AdManager().nativeAd!=null?
          Container(
            height: 200, // 设置广告容器高度
            margin: EdgeInsets.only(bottom: 10),
            child: AdWidget(
              ad: AdManager().nativeAd!, // 从AdManager获取广告
            ),
          ):SizedBox(),*/

              if("${globalData.appInfo.soft?.serviceUrl}".length>6)ListTileZdy(
                title: Text("联系我们".tr,style: TextStyle(fontSize: 16,color: AppStyles.colorPageText),),
                leading: Icon(Icons.headset_mic,color: AppStyles.colorPageText,),
                trailing: Icon(Icons.arrow_forward_ios,color: AppStyles.colorPageText),
                onTap: () {
                    launchUrl(Uri.parse("${globalData.appInfo.soft?.serviceUrl}")); //

                },
              ),


              ListTileZdy(
                title: Text("隐私政策".tr,style: TextStyle(fontSize: 16,color: AppStyles.colorPageText),),
                leading: Icon(Icons.abc_outlined,color: AppStyles.colorPageText,),
                trailing: Icon(Icons.arrow_forward_ios,color: AppStyles.colorPageText),
                onTap: () {
                  launchUrl(Uri.parse("${globalData.appInfo.soft?.deal}")); //

                },
              ),

              // 下面是推荐app

           // ... existing code ...
              if (globalData.appInfo.apps?.isNotEmpty==true)Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text("更多精彩应用".tr, style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: AppStyles.colorPageText
                  )),
                ],
              ),

if(globalData.appInfo.apps?.isNotEmpty==true)
  for (var element in globalData.appInfo.apps!)
  ListTileZdy(
    title: Text("${element.title}",style: TextStyle(fontSize: 16,color: AppStyles.colorPageText),),
    leading: Image.network(
      "${element.logo}"?? "https://via.placeholder.com/50", // 使用网络图片，提供默认占位图
      width: 50,
      height: 50,
      errorBuilder: (context, error, stackTrace) =>
        Icon(Icons.apps, size: 50), // 图片加载失败时显示默认图标
    ),
    trailing: Icon(Icons.arrow_forward_ios,color: AppStyles.colorPageText),
    onTap: () {
      if ("${element.updateUrl}".length>4) {
        launchUrl(Uri.parse("${element.updateUrl}")); // 点击跳转到应用商店
      }
    },
  ),

// ... existing code ...





            ],
          ))

        ],
      ),
    );
  }


// ... 其他代码保持不变 ...

Widget ListTileZdy({
  Widget? title,
  Widget? trailing,
  Widget? leading,
  Function? onTap,
}){
  return Container(
    margin: EdgeInsets.all(10),

    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(16),
      gradient: LinearGradient(
        begin: Alignment.centerLeft,
        end: Alignment.centerRight,
        colors: [
          commonFuc.hexToColor("#ff8177"),

          //commonFuc.hexToColor("#000000"),
          commonFuc.hexToColor("#b12a5b"),
          /*backgroundColor,
              backgroundColor.withOpacity(0.8),
              backgroundColor.withOpacity(0.5),*/
        ],
      ),
    ),

    child: ListTile(
      title: title,
      trailing: trailing,
      leading: leading,
      onTap: onTap != null ? () => onTap() : null,
    ),
  );
}

// ... 其他代码保持不变 ...





}


